﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>WebSocket Test</title>
</head>
<body>
    <script language="javascript" type="text/javascript">

        var wsUri = "ws://localhost:5000/";
        var sid,toId;
        var output;

        function init() {
            output = document.getElementById("output");
            testWebSocket();
        }

        function testWebSocket() {
            sid = getQueryString("sid");
            if (!sid) {
                sid = '1';
            }
            toId = getQueryString("toId");
            if (!toId) {
                toId = '2';
            }
            wsUri += "?sid=" + sid;
            websocket = new WebSocket(wsUri);
            websocket.onopen = function (evt) {
                onOpen(evt)
            };
            websocket.onclose = function (evt) {
                onClose(evt)
            };
            websocket.onmessage = function (evt) {
                onMessage(evt)
            };
            websocket.onerror = function (evt) {
                onError(evt)
            };
        }

        function onOpen(evt) {
            writeToScreen("CONNECTED");
            doSend(JSON.stringify({ fromId: sid, toId: toId, MessageType: 'text', content: 'hello,I am opening for you!' }));
        }

        function onClose(evt) {
            writeToScreen("DISCONNECTED");
        }

        function onMessage(evt) {
            writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data + '</span>');
            //websocket.close();
        }

        function onError(evt) {
            writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
        }

        function doSend(message) {
            writeToScreen("SENT: " + message);
            websocket.send(message);
        }

        function writeToScreen(message) {
            var pre = document.createElement("p");
            pre.style.wordWrap = "break-word";
            pre.innerHTML = message;
            output.appendChild(pre);
        }

        function getQueryString(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        } 

        window.addEventListener("load", init, false);
    </script>
    <h2>WebSocket Test</h2>
    <div id="output"></div>
</body>
</html>